package com.xiaoye.qbproject.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoye.qbproject.domain.QbWarfareExamples;
import com.xiaoye.qbproject.exception.ServiceException;
import com.xiaoye.qbproject.mapper.QbWarfareExamplesMapper;
import com.xiaoye.qbproject.redis.RedisCache;
import com.xiaoye.qbproject.service.QbWarfareExamplesService;
import com.xiaoye.qbproject.util.StringUtils;
import com.xiaoye.qbproject.vo.QbWarfareExamplesImportV2Vo;
import com.xiaoye.qbproject.vo.dropDown.QbWarfareExamplesDropDownVo;
import io.jsonwebtoken.lang.Collections;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.utils.DateUtils;
import org.apache.jena.ontology.*;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.xiaoye.qbproject.redis.RedisConstant.QB_WARFARE_EXAMPLES;
import static com.xiaoye.qbproject.redis.RedisConstant.QB_WARFARE_EXAMPLES_DROPDOWN;

/**
 * @author Administrator
 * @description 针对表【QB_WARFARE_EXAMPLES(战争战例)】的数据库操作Service实现
 * @createDate 2024-12-30 14:37:14
 */
@Slf4j
@Service
@Transactional
public class QbWarfareExamplesServiceImpl extends ServiceImpl<QbWarfareExamplesMapper, QbWarfareExamples>
        implements QbWarfareExamplesService {

    @Autowired
    private RedisCache redisCache;

    public static void main(String[] args) {
        String dateStr = "1904年2月8日";
        Date date = processDate(dateStr);
        System.out.println("转换后的日期：" + DateUtils.formatDate(date, "yyyy-MM-dd HH:mm:ss"));
    }

    public static Date processDate(String dateStr) {
        if (StringUtils.isBlank(dateStr)) {
            return null;
        }
        // 1904年2月8日
        Date date = DateUtils.parseDate(dateStr, new String[]{"yyyy年MM月dd日", "yyyy年MM月", "yyyy年"});
        return date;
    }

    @Override
    @Async("async-executor")
    public void importExcel(List<QbWarfareExamples> qbWarfareExamples) {

        if (StringUtils.isNull(qbWarfareExamples) || qbWarfareExamples.isEmpty()) {
            throw new ServiceException("导入战例数据不能为空！");
        }
        List<QbWarfareExamples> oldInfos = baseMapper.selectList(Wrappers.<QbWarfareExamples>lambdaQuery()
                .select(QbWarfareExamples::getEventId, QbWarfareExamples::getId)
        );
        // list转成map
        HashMap<String, String> eventAndIdMap = new HashMap<>();
        oldInfos.forEach(info -> {
            eventAndIdMap.put(info.getEventId(), info.getId());
        });
        // 列表拆分成 1000条一组
        // 每个批次处理的元素数量
        int batchSize = 1000;
        // list 的大小
        int listSize = qbWarfareExamples.size();
        for (int i = 0; i < listSize; i += batchSize) {
            // 结束索引不能超过 list 的大小
            int endIndex = Math.min(i + batchSize, listSize);
            List<QbWarfareExamples> subList = qbWarfareExamples.subList(i, endIndex);
            // 分批导入
            doImportExcel(subList, eventAndIdMap);
        }

    }

    /**
     * @description: 战例下拉数据
     * @author: ChenYao
     * @return: java.util.List<com.xiaoye.qbproject.vo.dropDown.QbWarfareExamplesDropDownVo>
     * @ceateDate: 2025-01-02 13:26
     */

    @Override
    public List<QbWarfareExamplesDropDownVo> dropDown() {
        List<QbWarfareExamplesDropDownVo> qbWarfareExamplesDropDownVos = redisCache.getCacheObject(QB_WARFARE_EXAMPLES_DROPDOWN);
        if (qbWarfareExamplesDropDownVos != null) {
            return qbWarfareExamplesDropDownVos;
        }
        qbWarfareExamplesDropDownVos = baseMapper.dropDown();
        redisCache.setCacheObject(QB_WARFARE_EXAMPLES_DROPDOWN, qbWarfareExamplesDropDownVos, 10, TimeUnit.MINUTES);
        return qbWarfareExamplesDropDownVos;
    }

    @Override
    public void delCache() {
        redisCache.deleteObject(QB_WARFARE_EXAMPLES_DROPDOWN);
        redisCache.deleteObject(QB_WARFARE_EXAMPLES);
    }

    /**
     * @param ids
     * @param response
     * @description: 导出战例数据到owl文件
     * @author: ChenYao
     * @return: void
     * @ceateDate: 2025-01-03 16:36
     */
    @Override
    public void exportOwl(String[] ids, HttpServletResponse response) {
        if (ids == null || ids.length == 0) {
            throw new ServiceException("请选择要导出的数据");
        }
        List<QbWarfareExamples> qbWarfareExamples = baseMapper.selectList(Wrappers.<QbWarfareExamples>lambdaQuery().in(QbWarfareExamples::getId, Arrays.asList(ids)));
        if (Collections.isEmpty(qbWarfareExamples)) {
            return;
        }
        // 创建一个空的模型
        Model model = ModelFactory.createDefaultModel();

        // 创建一个本体（这里以匿名本体为例）
        OntModel ontModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, model);

        // 定义命名空间（这里以示例命名空间为例）
        String ns = "http://example.com/qbWarfareExamples#";
        ontModel.setNsPrefix("qbWarfareExamples", ns);

        // 定义类
        OntClass zbClass = ontModel.createClass(ns + "ZbInfo");

        // 定义属性
        OntProperty nameProperty = ontModel.createOntProperty(ns + "name");
        OntProperty title = ontModel.createOntProperty(ns + "title");
        OntProperty classifyLabel = ontModel.createOntProperty(ns + "classifyLabel");
        OntProperty equipLabel = ontModel.createOntProperty(ns + "equipLabel");
        OntProperty fightTime = ontModel.createOntProperty(ns + "fightTime");
        OntProperty fightAddress = ontModel.createOntProperty(ns + "fightAddress");
        OntProperty jd = ontModel.createOntProperty(ns + "jd");
        OntProperty wd = ontModel.createOntProperty(ns + "wd");
        OntProperty translation = ontModel.createOntProperty(ns + "translation");


        // 假设zbInfos是一个包含数据的集合

        // 创建个体并填充数据
        for (QbWarfareExamples warfareExamples : qbWarfareExamples) {
            Individual individual = ontModel.createIndividual(ns + warfareExamples.getId(), zbClass);
            individual.addProperty(nameProperty, warfareExamples.getName());
            individual.addProperty(title, warfareExamples.getTitle());
            String classifyLabel1 = warfareExamples.getClassifyLabel();
            if (StringUtils.isNotBlank(classifyLabel1)) {
                individual.addProperty(classifyLabel, classifyLabel1);
            }
            String equipLabel1 = warfareExamples.getEquipLabel();
            if (StringUtils.isNotBlank(equipLabel1)) {
                individual.addProperty(equipLabel, equipLabel1);
            }
            individual.addProperty(fightTime, DateUtils.formatDate(warfareExamples.getFightTime(), "yyyy-MM-dd HH:mm:ss"));
            String fightAddress1 = warfareExamples.getFightAddress();
            if (StringUtils.isNotBlank(fightAddress1)) {
                individual.addProperty(fightAddress, fightAddress1);
            }
            individual.addProperty(jd, String.valueOf(warfareExamples.getJd()));
            individual.addProperty(wd, String.valueOf(warfareExamples.getWd()));
            individual.addProperty(translation, warfareExamples.getTranslation());

        }
        // 将本体写入文件
        try (ServletOutputStream outputStream = response.getOutputStream()
        ) {
            ontModel.write(outputStream, "RDF/XML-ABBREV"); // 使用RDF/XML格式导出
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void saveWarfareExamlesV2(List<QbWarfareExamplesImportV2Vo> qbWarfareExamplesImportV2Vos, String countryName) {

        // 获取所有战例
        List<QbWarfareExamples> qbWarfareExamples = baseMapper.selectList(Wrappers.<QbWarfareExamples>lambdaQuery()
                .select(QbWarfareExamples::getId, QbWarfareExamples::getTitle)
        );
        HashMap<String, QbWarfareExamples> map = new HashMap<>();
        qbWarfareExamples.forEach(e -> {
            map.put(e.getTitle(), e);
        });
        for (QbWarfareExamplesImportV2Vo qbWarfareExamplesImportV2Vo : qbWarfareExamplesImportV2Vos) {
            String name = qbWarfareExamplesImportV2Vo.getName();
            String title = qbWarfareExamplesImportV2Vo.getTitle();
            if (StringUtils.isBlank(name) || StringUtils.isBlank(title)) {
                continue;
            }

            QbWarfareExamples zbInfo = new QbWarfareExamples();
            BeanUtils.copyProperties(qbWarfareExamplesImportV2Vo, zbInfo);
            zbInfo.setFightTime(processDate(qbWarfareExamplesImportV2Vo.getFightTimeStr()));

            QbWarfareExamples old = map.get(title);
            if (old != null) {
                zbInfo.setId(old.getId());
                baseMapper.updateById(zbInfo);
            } else {
                baseMapper.insert(zbInfo);
            }
            map.put(title, zbInfo);

        }

    }

    @Async("async-executor")
    public void doImportExcel(List<QbWarfareExamples> qbWarfareExamples, Map<String, String> eventAndIdMap) {
        // 导入数据
        for (QbWarfareExamples warfareExamples : qbWarfareExamples) {
            // 判断事件ID是否存在
            String eventId = warfareExamples.getEventId();
            if (eventAndIdMap.containsKey(eventId)) {
                String id = eventAndIdMap.get(eventId);
                warfareExamples.setId(id);
                // 存在更新
                baseMapper.updateById(warfareExamples);
                log.info("EventId:{};标题:{}; 导入数据[更新]成功！", eventId, warfareExamples.getTitle());
                continue;
            }
            // 存在更新,不存在新增
            baseMapper.insert(warfareExamples);
            log.info("EventId:{};标题:{}; 导入数据[新增]成功！", eventId, warfareExamples.getTitle());
        }

    }
}




